//
//  SVProgressHUD+Ex.swift
//  TSSmalCoacopods_Example
//
//  Created by 100Years on 2025/3/11.
//  Copyright © 2025 CocoaPods. All rights reserved.
//
import Foundation
import ObjectiveC
import SVProgressHUD
extension SVProgressHUD {
    // 重写 moveToPoint:rotateAngle: 方法
    @objc dynamic func swizzledMoveToPoint(_ newCenter: CGPoint, rotateAngle angle: CGFloat) {
        // 调用原方法
        self.swizzledMoveToPoint(newCenter, rotateAngle: angle)
//        print("swizzledMoveToPoint swizzledMoveToPoint")
        // 使用运行时获取 hudView 属性
        if let hudView = getHudView() {
            if let containerView = containerView {
                hudView.center = CGPoint(x: containerView.bounds.size.width/2 + offsetFromCenter.horizontal, y: containerView.bounds.size.height/2 + offsetFromCenter.vertical)
            } else {
                hudView.center = CGPoint(x: newCenter.x + offsetFromCenter.horizontal, y: newCenter.y + offsetFromCenter.vertical)
            }
        }
    }
    
    // 获取 hudView 属性
    private func getHudView() -> UIVisualEffectView? {
        var count: UInt32 = 0
        guard let classProperties = class_copyPropertyList(SVProgressHUD.self, &count) else {
            return nil
        }
        
        for i in 0..<Int(count) {
            let property = classProperties[i]
            let propertyName = String(cString: property_getName(property))
            if propertyName == "hudView" {
                let hudView = value(forKey: propertyName) as? UIVisualEffectView
                free(classProperties)
                return hudView
            }
        }
        
        free(classProperties)
        return nil
    }
}

// 方法交换
extension SVProgressHUD {
    static func swizzleMethods() {
        // 手动创建选择器
        let originalSelector = NSSelectorFromString("moveToPoint:rotateAngle:")
        let swizzledSelector = #selector(SVProgressHUD.swizzledMoveToPoint(_:rotateAngle:))
        
        let originalMethod = class_getInstanceMethod(SVProgressHUD.self, originalSelector)
        let swizzledMethod = class_getInstanceMethod(SVProgressHUD.self, swizzledSelector)
        
        if let originalMethod = originalMethod, let swizzledMethod = swizzledMethod {
            method_exchangeImplementations(originalMethod, swizzledMethod)
        }
    }
}
